package com.example.pertecttime.activity.login;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import com.example.pertecttime.entity.User;
import com.example.pertecttime.tools.MD5Utils;
import com.example.pertecttime.tools.Ts;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by 半生瓜 on 2017/7/12.
 */
@Slf4j
public class loginPresenter extends loginContract.Presenter {

    private SharedPreferences sp;
    private boolean remembercode, antucode;

    @Override
    public void dologin(boolean remembercode, boolean antucode, String un, String psd) {

        Ts T = new Ts(view.getContext());
        this.remembercode = remembercode;
        this.antucode = antucode;
        rxManager.add(modle.getLoginModel(new User(un, MD5Utils.md5(psd)))
                        .subscribe(result -> {
                            Log.i("login", "登陆" + result.getErrorCode());
                            if (result.getErrorCode() == 0) {
                                view.loginSuccess(result.getData());
                            } else {
                                view.loginFail(result.getErrorCode());
                            }
                        }, e -> {
//                    hideLoadingDialog();
                    T.show_s("登入错误");
                        })
        );


    }

    @Override
    public void savaRecord(Boolean r, Boolean antu, String un, String psd) {
        SharedPreferences.Editor editor = sp.edit();
        if (r) {
            editor.putBoolean("remember", true);
            editor.putString("username", un);
            editor.putString("password", psd);
            if (antu) {
                editor.putBoolean("antulogin", true);
            } else editor.putBoolean("antulogin", false);

        } else {
            editor.putBoolean("remember", false);
        }
        editor.commit();

    }

    @Override
    public void onCreate(Context c) {
        sp = c.getSharedPreferences("userInfo", 0);

        boolean choseRemember = sp.getBoolean("remember", false);
        boolean choseAutoLogin = sp.getBoolean("antulogin", false);
        //// TODO: 2017/7/19
        if (choseRemember) {
            String username = sp.getString("username", "");
            String password = sp.getString("password", "");
            view.onCheckBoxResult(choseRemember, choseAutoLogin, username, password);
            if (choseAutoLogin) {
                dologin(choseRemember, choseAutoLogin, username, password);
            }
        }
    }


}
